package api

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"zinx_websokect_poker/zinx/ziface"
	"zinx_websokect_poker/zinx/znet"
	"zinx_websokect_poker/zinx_app/poker_game/core"
	"zinx_websokect_poker/zinx_app/poker_game/http"
	json2 "zinx_websokect_poker/zinx_app/poker_game/json"
	"zinx_websokect_poker/zinx_app/poker_game/log"
	"zinx_websokect_poker/zinx_app/poker_game/protocol"
)

type GoRoomApi struct {
	znet.BaseRouter
}

type jsonMsg struct {
	Cmd interface{}	 `json:"cmd"`
	Msg *protocol.JoinRoom	 `json:"msg"`
}

func (g *GoRoomApi) Handle(request ziface.IRequest) {
	//TODO 获取房号,解析数据，再加入房间或者
	//接受消息，joinRoom，先获取用户房间信息，无则根据传进来的房号寻找房间，没房号则自动匹配，找不到房间则新建一个房间。
	//返回一个房间实体后，调用房间的joinRoom将玩家添加进去。

	fmt.Println("尝试加入房间")
	jr :=  jsonMsg{}
	data := request.GetData()
	err:=json.Unmarshal(data,&jr)
	//解析失败会报错，如json字符串格式不对，缺"号，缺}等。
	if err!=nil{
		fmt.Println(err)
	}
	//fmt.Println(jr)
	//fmt.Println(*jr.Msg)

	//pid ,_:= request.GetConnection().GetProperty("Pid")
	//pid2 := pid.(uint32)
	//play := core.PlayerMgrObj.GetPlayerByPid(pid2)
	//oo, err := request.GetConnection().GetProperty("Oc")
	//if err!=nil{
	//	fmt.Println(err)
	//}
	//o:= oo.(*core.Occupant)
	p, _ := request.GetConnection().GetProperty("Pid")
	pid := p.(uint32)
	o := core.OccupantMgrObj.GetOccupantByPid(pid)

	msg := jr.Msg

	//fmt.Println(jr.Msg)

	r := core.GetRoom(o.RoomID)
	fmt.Println("o.RoomID: ", o.RoomID)
	if r != nil {
		//TODO 掉线重连操作
		fmt.Println("掉线重连操作",*o)
	} else {
		//var r ziface.IRoom
		if len(msg.RoomId) == 0 {
			//匹配空房
			r = core.FindRoom()
		}else {
			r = core.GetRoom(msg.RoomId)
		}

		//寻找房间
		if  r == nil {
			//没有房间返回失败信息
			resp := &core.JRR{
				Code: 1,
				IsCreateRoom: 0,
			}
			jsonStu := json2.Jsonmr(4, resp)
			o.WriteMsg(jsonStu)
		} else {
			//r不为空时是一个房间实体
			fmt.Println("玩家加入房间",r.GetNumber())
			r.JoinRoom(jr.Msg, o, 0)
		}

	}

}

type CreateRoomApi struct {
	znet.BaseRouter
}

type createRoomMsg struct {
	Cmd interface{}	 `json:"cmd"`
	Msg *protocol.CreateRoom	 `json:"msg"`
}

func (c *CreateRoomApi) Handle(request ziface.IRequest){
	//{"max":9,"sb":5,"bb":10,"chips":1000}
	fmt.Println("尝试创建房间")
	jr :=  createRoomMsg{}
	data := request.GetData()
	err:=json.Unmarshal(data,&jr)
	//解析失败会报错，如json字符串格式不对，缺"号，缺}等。
	if err!=nil{
		fmt.Println(err)
	}

	m := jr.Msg

	p, _ := request.GetConnection().GetProperty("Pid")
	pid := p.(uint32)
	o := core.OccupantMgrObj.GetOccupantByPid(pid)
	r := core.GetRoom(o.RoomID)
	fmt.Println(&o)

	if r != nil {
		//TODO 掉线重连操作
		fmt.Println("当前在房间中，无法创建",*o)
		//没有房间返回失败信息
		resp := &core.JRR{
			Code: 1,
			IsCreateRoom: 1,
		}
		jsonStu := json2.Jsonmr(4, resp)
		o.WriteMsg(jsonStu)
	}else {
		max := m.Max
		sb := m.Sb
		bb := m.Bb
		chips := m.Chips
		timeout := m.Time

		room := core.NewRoom(uint8(max), uint32(sb), uint32(bb), uint32(chips), uint32(timeout), o.OutId, o)
		core.SetRoom(room)
		// 创建房间，访问创房接口
		http.Addgameroom(&http.Groom{
			Owner:       room.Owner,
			Number:      room.Number,
			DraginChips: room.DraginChips,
			SB:          room.SB,
			BB:          room.BB,
			Max:         room.Max,
			RoomTime:    room.RoomTime,
		})

		log.Info("Room-CreateRoom", "【创建房间】房间号：" + room.Number +
			"房主：" + o.Nickname + "OutId :" +strconv.Itoa(int(o.OutId)))

		//创建房间后加入房间，加入房间后
		room.JoinRoom("", o, 1)

		//创建房间后加入房间坐下
		//room.SitDown(4, o)

	}
}

type SitDownApi struct {
	znet.BaseRouter
}

func (c *SitDownApi) Handle(request ziface.IRequest){
	//oo, err := request.GetConnection().GetProperty("Oc")
	//if err!=nil{
	//	fmt.Println(err)
	//}
	//o:= oo.(*core.Occupant)
	p, _ := request.GetConnection().GetProperty("Pid")
	pid := p.(uint32)
	o := core.OccupantMgrObj.GetOccupantByPid(pid)

	fmt.Println(&o)

	fmt.Println("尝试坐下")
	jr :=  json2.Jsrep{}
	data := request.GetData()
	err := json.Unmarshal(data,&jr)

	//解析失败会报错，如json字符串格式不对，缺"号，缺}等。
	if err!=nil{
		fmt.Println(err)
	}

	m := jr.Msg.(map[string]interface{})

	//pos := json2.Toint(m["pos"].(string))
	var value uint8
	switch reflect.ValueOf(m["pos"]).Kind() {
	case reflect.String:
		if s,err := strconv.Atoi(m["pos"].(string));err==nil{
			value = uint8(s)
		}
	case reflect.Float64:
		value = uint8(m["pos"].(float64))
	default:
		value = 0
	}



	r := core.GetRoom(o.RoomID)

	if r == nil {
		//不在房间中，无法使用坐下操作
		fmt.Println("不在房间中，无法使用坐下操作")
		return
	}else {
		r.SitDown(value, o)
		fmt.Println("坐下成功")
	}

}

type StandUpApi struct {
	znet.BaseRouter
}

func (c *StandUpApi) Handle(request ziface.IRequest){
	p, _ := request.GetConnection().GetProperty("Pid")
	pid := p.(uint32)
	//获取玩家信息
	o := core.OccupantMgrObj.GetOccupantByPid(pid)

	//站起操作
	if r := o.GetRoom(); r!=nil {
		r.StandUp(o)
	}else {
		//玩家不在房间

	}

}

type GetRoomInfoApi struct {
	znet.BaseRouter
}

func (g *GetRoomInfoApi) Handle(request ziface.IRequest){

	o := GetOccupantByRequest(request)

	//获取玩家房间
	if roomId := o.RoomID; len(roomId) > 0 {
		r := core.GetRoom(roomId)
		r.GetRoomInfo(o)
	}else {
		//玩家不在房间
		jsonStu := json2.Jsonmr(6, nil)
		o.WriteMsg(jsonStu)
	}

}


func GetOccupantByRequest(request ziface.IRequest) *core.Occupant{
	p, _ := request.GetConnection().GetProperty("Pid")
	pid := p.(uint32)
	//获取玩家信息
	o := core.OccupantMgrObj.GetOccupantByPid(pid)

	return o
}